<?php

namespace Admin\Controller;

/**
 * 积分兑换
 *
 * Class PointController
 * @package Admin\Controller
 */
class PointController extends PublicController
{
    private $goods;
    private $goodsImages;
    private $category;

    /**
     *
     * 构造函数，用于导入外部文件和公共方法
     */
    public function _initialize()
    {
        $this->category = M("Category");
        $this->goods = M('goods');
        $this->goodsImages = M('goods_images');
        $this->assign('modules', '积分兑换');
    }

    /**
     * 积分商品列表
     */
    public function goodsList()
    {
        $this->assign('title', '积分商品');

        $where = "1 = 1";
        if (isset($_GET['keyword'])) {
            $where .= " AND name like '%" . trim($_GET['keyword']) . "%'";
            $this->assign('keyword', trim($_GET['keyword']));
        }
        $count = $this->goods->where($where)->count();
        $perPage = 20;
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 0;
        $totalPage = ceil($count / $perPage);
        $pageObj = $this->page_index($count, $totalPage, $page);
        $list = $this->goods->where($where)->order('sort = 0, sort asc, id desc')->limit($page * $perPage, $perPage)->select();
        foreach ( $list as $k=>$v ) {
            $cate = $this->category->where("id=".$v['cate_id'])->find();
            $list[$k]['cate_name'] = $cate['name'];
        }
        $this->assign('list', $list);
        $this->assign('pageObj', $pageObj);
        $this->display();
    }

    /**
     * 添加商品
     */
    public function addGoods()
    {
        $this->assign('title', '添加商品');
        if (intval($_GET['id'])) {
            $goodsId = intval($_GET['id']);
            $detail = $this->goods->where(['id' => $goodsId, 'is_del' => 0])->find();
            if (!empty($detail)) {
                $goodsImages = $this->goodsImages->where('goods_id = ' . $goodsId)->order('id asc')->select();
                $detail['images'] = array_column($goodsImages, 'image');
                $this->assign('title', '修改商品信息');
                $this->assign("detail", $detail);
            }
        }
        $cate = $this->category->select();
        $this->assign("cate",$cate);
        $this->display();
    }

    /**
     * 保存商品信息
     */
    public function saveGoods()
    {
        $goodsImages = explode(',', str_replace('/Data/', '', $_POST['images']));
        if (empty($goodsImages)) {
            $this->error('请上传商品图片');
        }
        $goodsData = array(
            'name'      => $_POST['name'],
            'cate_id'   => $_POST['cate_id'],
            'cover'     => $goodsImages[0],
            'content'   => $_POST['content'],
            'point'     => $_POST['point'],
            'in_stock'  => $_POST['in_stock'],
            'is_show'   => $_POST['is_show'],
            'sort'      => empty($_POST['sort']) ? 0 : intval($_POST['sort']),
            'recommend' => empty($_POST['recommend']) ? 0 : intval($_POST['recommend']),
        );

        if (isset($_POST['id']) && !empty($_POST['id'])) {
            $id = intval($_POST['id']);
            $this->goods->where('id=' . $id)->save($goodsData);
            $this->goodsImages->where('goods_id = ' . $id)->delete();
        } else {
            $goodsData['create_at'] = date('Y-m-d H:i:s');
            $id = $this->goods->add($goodsData);
        }

        // 保存图片
        foreach ($goodsImages as $index => $image) {
            $this->goodsImages->add(['goods_id' => $id, 'image' => $image, 'sort' => $index + 1]);
        }

        $this->success('操作成功.', U('goodsList'));
    }

    /**
     * 上下架操作
     */
    public function del()
    {
        $goodsId = intval($_GET['did']);
        $goods = $this->goods->where('id=' . $goodsId)->find();
        if (!$goods) {
            $this->error('商品不存在');
        }

        $isShow = $goods['is_show'] == 1 ? 0 : 1;
        $result = $this->goods->where('id=' . $goodsId)->save(['is_show' => $isShow]);
        if ($result) {
            $this->success('操作成功.', 'goodsList');
        } else {
            $this->error('操作失败.');
        }
    }

    /**
     * 订单列表
     */
    public function orderList()
    {
        $this->assign('title', '积分兑换');
        $where = "1 = 1";
        $perPage = 20;
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 0;
        $count = M('point_order')->join('lr_goods g on g.id = lr_point_order.goods_id')->where($where)->count();
        $totalPage = ceil($count / $perPage);
        $pageObj = $this->page_index($count, $totalPage, $page);
        $list = M('point_order')->where($where)->join('lr_goods g on g.id = lr_point_order.goods_id')
            ->field('g.name, g.cover, g.point, lr_point_order.id,lr_point_order.goods_id, lr_point_order.status,in_stock, lr_point_order.receiver, lr_point_order.mobile')
            ->order('lr_point_order.id desc')->limit($page * $perPage, $perPage)->select();

        $this->assign('list', $list);
        $this->assign('pageObj', $pageObj);
        $this->display();
    }

    /**
     * 订单详情
     */
    public function order()
    {
        $this->assign('title', '订单详情');

        $orderId = intval($_GET['id']);
        if (empty($orderId)) {
            $this->error('商品不存在');
        }

        $orderInfo = M('point_order')->where('id = ' . $orderId)->find();
        if (empty($orderInfo)) {
            $this->json_error("订单信息错误");
        }
        $orderInfo['goods'] = M('goods')->where('id = ' . $orderInfo['goods_id'])->field('id, name, cover')->find();
        $this->assign('detail', $orderInfo);
        $this->assign('post', $this->getPost());
        $this->display();
    }

    /**
     * 订单发货
     */
    public function updatePost()
    {
        $postCode = $_POST['post_code'];
        $postNum = $_POST['post_num'];
        $orderId = intval($_POST['order_id']);
        $orderInfo = M('point_order')->where('id = ' . $orderId)->find();
        if (!empty($orderInfo) && $orderInfo['status'] == 10) {
            $result = M('point_order')->where('id=' . $orderId)->save([
                'post_code' => $postCode,
                'post_num'  => $postNum,
                'status'    => 20,
            ]);
            if ($result) {
                $this->success('操作成功.', 'orderList');
            } else {
                $this->error('操作失败.');
            }
        }

    }

    /**
     * 获取物流信息
     */
    private function getPost()
    {
        $post = C("WULIU");
        $postArray = array();
        foreach ($post as $key => $value) {
            $postArray[$key] = $value[0];
        }
        return $postArray;
    }

    /**
     * 商品图片上传
     */
    public function goodsImageUpload()
    {
        //上传图片
        if (!empty($_FILES["file"]["tmp_name"])) {
            $info = $this->upload_images($_FILES["file"], array('jpg', 'png', 'jpeg'), 'pointGoods/' . date('Ymd'));
            if (!is_array($info)) {
                $this->error($info);
            } else {
                exit('UploadFiles/' . $info['savepath'] . $info['savename']);
            }
        }
    }

    /**
     * 商品分类列表
     */
    public function cateList()
    {
        $this->assign('title', '商品分来');

        $where = "1 = 1";
        if (isset($_GET['keyword'])) {
            $where .= " AND name like '%" . trim($_GET['keyword']) . "%'";
            $this->assign('keyword', trim($_GET['keyword']));
        }
        $count = $this->goods->where($where)->count();
        $perPage = 20;
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 0;
        $totalPage = ceil($count / $perPage);
        $pageObj = $this->page_index($count, $totalPage, $page);
        $list = $this->category->where($where)->order('id desc')->limit($page * $perPage, $perPage)->select();

        $this->assign('list', $list);
        $this->assign('pageObj', $pageObj);
        $this->display();
    }

    /**
     * 商品分类添加
     */
    public function cateAdd()
    {
        if ( !empty(I("get.id"))) {
            $this->assign('title', '商品分来编辑');
            $news = $this->category->where("id=".I("get.id"))->find();
            $this->assign("news",$news);
        }else {
            $this->assign('title', '商品分来添加');
        }

        $this->display();
    }

    public function  cateSave()
    {
        $data = array(
            'name'      => $_POST['name'],
        );

        if (isset($_POST['id']) && !empty($_POST['id'])) {
            $id = intval($_POST['id']);
            $this->category->where('id=' . $id)->save($data);
        } else {
            $data['addtime'] = date('Y-m-d H:i:s');
            $id = $this->category->add($data);
        }

        $this->success('操作成功.', U('cateList'));
    }

    /**
     *删除
     */
    public function cateDel()
    {
        $id = intval($_REQUEST['did']);
        $result = $this->category->where('id='.$id)->delete();
        if( $result ){
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }
}